package org.chen.web.controller.admin;


import io.swagger.annotations.*;
import org.chen.common.RespUtils;
import org.chen.model.Roles;
import org.chen.model.User;
import org.chen.respmsg.RespEnum;
import org.chen.service.RolesService;
import org.chen.service.UserService;
import org.chen.vo.RespBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Api(tags = "用户管理")
@RestController
@RequestMapping("/admin")
public class UserController {
    @Autowired
    UserService service;

    @Autowired
    RolesService rolesService;

    @ApiOperation(value = "获取除了当前用户的所有用户",notes = "keyword可不传")
    @ApiImplicitParam(name="keyword",value = "用户名称",paramType = "query",required = false,dataType = "String")
    @ApiResponses({
            @ApiResponse(code = 0,message = "成功"),
            @ApiResponse(code = 200,message = "成功")
    })
    @GetMapping("/users")
    public RespBean<List<User>> getAllUsers(String keyword){
        List<User> users = service.getAllUsers(keyword);
        return RespUtils.result(users, RespEnum.SUCCESS);
    }

    @GetMapping("/user/{id}")
    public RespBean<User> getUserById(@PathVariable("id") Integer id){
        User user = service.getUserById(id);
        return RespUtils.result(user, RespEnum.SUCCESS);
    }

    @ApiOperation(value = "禁用/启用用户",notes = "id一定要传")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name="id",value="用户ID",required=true,paramType="body",dataType = "int"),
            @ApiImplicitParam(name="enabled",value="是否启用",required=true,paramType="body",dataType = "boolean",defaultValue = "false")
    })
    @PutMapping("/user/enabled")
    public RespBean<String> enableUserById(Integer id, Boolean enabled){
        if (service.enableUserById(id,enabled)==1){
            return  RespUtils.result(RespEnum.UPDATE_SUCCESS);
        }
        return  RespUtils.result(RespEnum.UPDATE_FAIL);
    }

    @DeleteMapping("/user/{id}")
    public RespBean<String> delUserById(@PathVariable("id")Integer id){
        if (service.delUserById(id)==1){
            return  RespUtils.result(RespEnum.DELETE_SUCCESS);
        }
        return  RespUtils.result(RespEnum.DELETE_FAIL);
    }

    @GetMapping("/roles")
    public RespBean<List<Roles>> getAllUsers(){
        List<Roles> roles = rolesService.getAllRoles();
        return RespUtils.result(roles, RespEnum.SUCCESS);
    }

    @PutMapping("/user/role")
    public RespBean<String> updateUserRole(Integer id,Integer[] rids){
        if (rids==null||rids.length==0){
            return RespUtils.fail("rid不能为空");
        }
        if (service.updateUserRoles(id,rids)==rids.length){
            return  RespUtils.result(RespEnum.UPDATE_SUCCESS);
        }
        return  RespUtils.result(RespEnum.UPDATE_FAIL);
    }
}
